import time
import random
import json
from app.utils import WebMimicUtil, FakerUtil
from app.api.schemas import Lang
from app.api.services.translators.abstract_translate import AbstractTranslator
from app.api.services.translators.baidu.baidu_lang import BaiduLang


class BaiduTranslatorV2(AbstractTranslator):
    """
    百度翻译器类
    """

    _DEF_COOKIE = 'BAIDUID=65F932DA9707157D192E5F654A7C7378:FG=1; BAIDUID_BFESS=65F932DA9707157D192E5F654A7C7378:FG=1; PSTM=1724913673; BDRCVFR[5ig7pqb-tu6]=mk3SLVN4HKm; H_PS_PSSID=60600_60621_60628_60664_60677_60693; BIDUPSID=8EE78FE772BCEFEF7CB46B38B06F07F9; BA_HECTOR=2g8l25al042l2ha48h04a1ag1epks91jd06081u; ZFY=LiHLqcdH1mzUuuxYWAFkwauFvaU7z9oCi1Ty4HlkzSw:C; PSINO=6; delPer=0; BDORZ=FFFB88E999055A3F8A630C64834BD6D0; ab_sr=1.0.1_OWU0NzliNDI0Yjc1NzliZDY5ZDc2MDRhN2RmOWYxODJkNjhhMDRmNzc5NmNlMjJmNDcxYTlmMzkyOGZlNjZkN2IwMzk0YzQ2Zjc1NWNlYjYyY2VkYjc3NjdkZWMwZDM1NTVhYTE3NGI1MzY1NDkyY2ZjODY3MDNkMzNmNDRmZTU1NzgzNmQwNmIyODhiOTZiYjQ2Njk3NDdlNmViMDE5YQ==; RT="z=1&dm=baidu.com&si=d57d7f46-2ba0-4a18-81f1-564f5c5b1275&ss=m0eyv3r9&sl=6&tt=mgl&bcn=https%3A%2F%2Ffclog.baidu.com%2Flog%2Fweirwood%3Ftype%3Dperf&ld=rk1j"'
    _DEF_ACS_TOKEN = "1724839209117_1724918403282_ukOYVez7Aw/2ja3OOXAmZoEc29i3rFRSjy5jELBwI7SB0W0PuhKczQL5hOLJx+DG1uRArDXIjIfy7SaeWIck3v15uTmHtwoS8X2CR21kFj0k/5dmjlow6aem6J7WG7GS3USnhEjIc8p9nHwpgzMp2ogS48swnxkqIShR95Va99FrcE/8shO/2cn4TD+4JxI5t0vICcAdO32XGqDrBF/qafph9szUxueSWhwNov6LJOJpae2gW2BGpQq2EvW9Hij526VFME/6x6sdsiLhD6KB4jKHr5+sftW8IdgBUlnPKLoPBsvKhOGu2ILQLMNJQocnQwiQB2eaZ5VRQyeR9soEKd58oMFOEgC0W7/ADEjnb4ko2/mSKFK4ie2gNz1U5/SBsweIGk6zzUypMdiQGVg6F7KcF5vFug1/CN6qUnxNYn4Rj+k4J5cmQx7wydrHO9RQGeFnmj9Rdq5dKR5hPqTOtx4q0g+q4MyuhJX+XaSD/QSDYsT8r9GZ/7r8zBUSWFEV"

    def __init__(self) -> None:
        super().__init__(
            url="https://fanyi.baidu.com/ait/text/translate",
            content_type="application/json",
        )
        self._DEF_ACS_TOKEN = BaiduTranslatorV2._DEF_ACS_TOKEN
        self.orgin = "https://fanyi.baidu.com"
        self.referer = "https://fanyi.baidu.com/mtpe-individual/multimodal"
        self.langdetect = "https://fanyi.baidu.com/langdetect"
        self.cookie_url = (
            "https://fanyi.baidu.com/mtpe-individual/multimodal?query=hello&lang=en2zh"
        )

    def _get_request_url(self):
        return self.url

    def _get_headers(self):
        """
        获取请求头
        """
        headers = {
            "Accept-Language": "zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6",
            "Acs-Token": self._DEF_ACS_TOKEN,
            "Cache-Control": "no-cache",
            "Connection": "keep-alive",
            "Content-Type": self.content_type,
            "Cookie": BaiduTranslatorV2._DEF_COOKIE,  # self._get_cookie(),
            "Origin": self.orgin,
            "Pragma": "no-cache",
            "Referer": self.referer,
            "Sec-Fetch-Dest": "empty",
            "Sec-Fetch-Mode": "cors",
            "Sec-Fetch-Site": "same-origin",
            "User-Agent": FakerUtil().fake_user_agent(),
            "accept": "text/event-stream",
            "sec-ch-ua-mobile": "?0",
            "sec-ch-ua-platform": '"Windows"',
        }
        return headers

    def _get_body(self):
        """
        获取请求体
        """
        vars = self._get_thread_local_vars()
        return {
            "query": vars.content,
            "from": BaiduLang.from_lang(vars.src_lang).code,
            "to": BaiduLang.from_lang(vars.target_lang).code,
            "reference": "",
            "corpusIds": [],
            "qcSettings": ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11"],
            "needPhonetic": True,
            "domain": "common",
            "milliTimestamp": int(time.time() * 1000) + random.randint(1, 999),
        }

    def _get_cookie(self):
        cookies = WebMimicUtil().get_all_cookies(self.cookie_url)

        if not cookies:
            return BaiduTranslatorV2._DEF_COOKIE

        cookie_str = "; ".join(
            [f"{cookie['name']}={cookie['value']}" for cookie in cookies]
        )
        return cookie_str

    # def _detect_language(self, content):
    #     url = self.langdetect
    #     data = {"query": content}

    #     vars = self._get_thread_local_vars()
    #     response = self.http_client.post(
    #         url,
    #         vars.use_proxy,
    #         headers=self._get_headers(),
    #         json=data,
    #         verify=False,
    #         timeout=10,  # 设置请求超时时间
    #     )
    #     response.raise_for_status()  # 如果请求失败，抛出异常

    #     jsonObject = response.json()
    #     source_lang = jsonObject.get("lan")
    #     return BaiduLang.from_code(source_lang).lang

    def _parse_repsonse(self, response):
        """
        解析响应
        """
        try:
            events = response.text.split("\n\n")
            data = next(
                (
                    json.loads(event.split("\n")[1][6:])
                    for event in events
                    if event.startswith("event: message")
                    and '"data":{"event":"Translating","' in event
                ),
                None,
            )

            if not data or data.get("errno") != 0 or not data["data"]["list"]:
                raise ValueError("翻译失败，未返回翻译结果数据！")

            result = [para["dst"] for para in data["data"]["list"] if para["dst"]]
            return "\n".join(result)

        except (json.JSONDecodeError, KeyError, IndexError) as e:
            raise ValueError(f"解析响应失败，异常信息：{e}")
